package com.pxr.slt.client;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.pxr.tutorial.xmltest.R;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends ListActivity {
    /** Called when the activity is first created. */
	
	public static String SERVER_ADDRESS = "http://192.168.1.8:8084/SLT/";
	SharedPreferences androidRef;
	String userName;
	ArrayList<HashMap<String, String>> tweets;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
              
        androidRef = getSharedPreferences("username", MODE_PRIVATE);
        userName = androidRef.getString("username","");
        if(userName.length()<=0){
        	Intent intent = new Intent(Main.this, Login.class);
            startActivity(intent);
        }
        
        tweets = new ArrayList<HashMap<String, String>>();
        JSONObject json = JSONfunctions.getJSONfromURL(SERVER_ADDRESS + "message/json");
                
        try{
        	
        	JSONArray  messages = json.getJSONArray("messages");
        	
	        for(int i=0;i<messages.length();i++){						
				HashMap<String, String> map = new HashMap<String, String>();	
				JSONObject e = messages.getJSONObject(i);
				
				map.put("id",  e.getString("messageId"));
	        	map.put("message", "" + e.getString("message"));
	        	map.put("user", "@" +  e.getString("username"));
	        	tweets.add(map);			
			}		
        }catch(JSONException e)        {
        	Toast.makeText(Main.this, e.toString(), Toast.LENGTH_SHORT).show();
        }
        
        ListAdapter adapter = new SimpleAdapter(this, tweets , R.layout.main, 
                        new String[] { "message", "user" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });
        
        setListAdapter(adapter);
        
        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);	
        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        		
        		@SuppressWarnings("unchecked")
				HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	 
        		//Toast.makeText(Main.this, "Tweet bericht '" + o.get("id") + "' werd aangeklikt. Functie??", Toast.LENGTH_SHORT).show(); 

			}
		});
        registerForContextMenu(lv);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.application_menu, menu);
        return true;
    }   
    
	public boolean onOptionsItemSelected(MenuItem item) {
    	Intent intent;
		switch (item.getItemId()) {
		case R.id.nieuw:   	
			intent = new Intent(Main.this, NewTweet.class);
            startActivity(intent);			
			return true;
		case R.id.afsluiten:
	        finish();
	        System.exit(0);
	        return true;
		case R.id.uitloggen:
			intent = new Intent(Main.this, Login.class);
			Editor editor = androidRef.edit();    
			editor.putString("username", "");
			editor.commit();
	        startActivity(intent);			
			return true;
		default:
		return super.onOptionsItemSelected(item);
		}
	}   
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	                                ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.tweet_menu, menu);
	}	
	
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    Intent intent = new Intent(Main.this, NewTweet.class);
	    final ListView lv = getListView();
	    HashMap<String, String> selectedTweet = (HashMap<String, String>) lv.getItemAtPosition(info.position);
	    
	    switch (item.getItemId()) {
	        case R.id.beantwoorden:
	            for(HashMap<String, String> tweet : tweets){
	            	if(tweet.get("id") == selectedTweet.get("id")){
	    	            intent.putExtra("action", "reply");
	    	            intent.putExtra("user", tweet.get("user"));
	    	            startActivity(intent);
	    	            return true;
	            		//Toast.makeText(Main.this, , Toast.LENGTH_SHORT).show();
	            	}
	            }
	            return true;
	        case R.id.retweet:
	            for(HashMap<String, String> tweet : tweets){
	            	if(tweet.get("id") == selectedTweet.get("id")){
	    	            intent.putExtra("action", "retweet");
	    	            intent.putExtra("user", tweet.get("user"));
	    	            intent.putExtra("message", tweet.get("message"));
	    	            startActivity(intent);
	    	            return true;
	            		//Toast.makeText(Main.this, , Toast.LENGTH_SHORT).show();
	            	}
	            }
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	}	
	
}